using System;
using System.Threading;
using System.Collections.Generic;
using OpenMetaverse;

namespace OpenFuse.Backend.Commands
{
	public class GetTopFoldersCommand : Command
	{
		public delegate void Result(SlSession session, Cache.Node parentNode, List<Cache.Node> nodes);

		Result _resultCallback;
		
		public GetTopFoldersCommand(SlSession session, Result resultCallback) : base(session)
		{
			_resultCallback = resultCallback;
		}
		
		public override void Run()
		{
			// Note we short circuit the hierarchy and use "My Inventory" as the root folder
			_session.Logger.Debug("Start GetTopFoldersCommand");
			if(_session.GridClient.Network.Connected)
			{
				OpenMetaverse.InventoryFolder root = _session.GridClient.Inventory.Store.RootFolder;

				string rootPath = "/" + _session.GridName + "/" + _session.FullName;
				
				Cache.FolderNode userFolder = _session.Cache.Nodes.GetById(_session.AvatarId.Guid) as Cache.FolderNode;
				if(userFolder == null)
					userFolder = new Cache.FolderNode(_session.AvatarId.Guid, rootPath, Guid.Empty, root.Version);
				
				// Get the folder contents from the inventory server
				List<Cache.Node> children = new List<Cache.Node>();
				List<InventoryBase> folderContents = _session.GridClient.Inventory.FolderContents(root.UUID, _session.AvatarId, true, true, OpenMetaverse.InventorySortOrder.ByName, 40000);
				if(folderContents != null)
				{
					foreach(InventoryBase e in folderContents)
					{
						Cache.Node newNode = null;
	
						if(e is OpenMetaverse.InventoryFolder)
						{
							OpenMetaverse.InventoryFolder f = (OpenMetaverse.InventoryFolder)e;
							newNode = _session.Cache.Nodes.GetById(f.UUID.Guid);
							if(newNode == null)
								newNode = new Cache.FolderNode(f.UUID.Guid, f.Name, f.ParentUUID.Guid, f.Version);
						}
						else if(e is OpenMetaverse.InventoryItem)
						{
							//TODO handle asset id of files
							OpenMetaverse.InventoryItem i = (OpenMetaverse.InventoryItem)e;
							newNode = _session.Cache.Nodes.GetById(i.UUID.Guid);
							if(newNode == null)
								newNode = new Cache.FileNode(i.UUID.Guid, i.Name, i.ParentUUID.Guid, i.AssetUUID.Guid, i.AssetType);
						} else {
							_session.Logger.Warn("This cannot happen");
						}
						 newNode.Parent = userFolder;
						children.Add(newNode);
					}
				}
				_session.Cache.Nodes.Save(userFolder);
				_resultCallback(_session, userFolder, children);
			}
			_session.Logger.Debug("End GetTopFoldersCommand");
		}
	}
}
